package com.aletto.general_store.configs;

import android.app.Activity;
import android.app.Application;
import android.content.pm.ActivityInfo;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import org.greenrobot.eventbus.EventBus;

public class EventBusAutoConfig implements Application.ActivityLifecycleCallbacks {

    private final FragmentSubscribeEventBus mEventBusFragmentLifecycleCallbacks;

    public EventBusAutoConfig() {
        mEventBusFragmentLifecycleCallbacks = new FragmentSubscribeEventBus();
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
//        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


        if (activity instanceof SubscribeEventBus) {
            EventBus.getDefault().register(activity);
        }

        if (activity instanceof AppCompatActivity) {
            FragmentManager supportFragmentManager = ((AppCompatActivity) activity).getSupportFragmentManager();
            supportFragmentManager.registerFragmentLifecycleCallbacks(mEventBusFragmentLifecycleCallbacks, true);
        }
    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        if (activity instanceof SubscribeEventBus) {
            EventBus.getDefault().unregister(activity);
        }

        if (activity instanceof AppCompatActivity) {
            FragmentManager supportFragmentManager = ((AppCompatActivity) activity).getSupportFragmentManager();
            supportFragmentManager.unregisterFragmentLifecycleCallbacks(mEventBusFragmentLifecycleCallbacks);
        }
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

}
